#include <vector>

#include "Client.h"

#define buffer_size 10000

Client::Client(string sock_type, int ipv) {
    if (sock_type == "tcp") {
        sockType = SOCK_STREAM;
    } else {
        sockType = SOCK_DGRAM;
    }

    if (ipv == 4) {
        IPv = AF_INET;
    } else {
        IPv = AF_INET6;
    }
}

void Client::Connect(string host, int port) {

    memset(&hints, 0, sizeof hints);
    hints.ai_family = IPv;
    hints.ai_socktype = sockType;


    ostringstream s;
    s << port;
    int aierr;
    int conerr;
    aierr = getaddrinfo(host.c_str(), s.str().c_str(), &hints, &serverInfo);

    #ifdef DEBUG
    if (aierr != 0) {
        cout << "Host not found\n";
    }
    #endif

    for (p = serverInfo; p != NULL; p = p->ai_next) {
        if ((sockfd = socket(p->ai_family, p->ai_socktype,
                p->ai_protocol)) == -1) {
            continue; //bad socket, try next
        }
        conerr = connect(sockfd, p->ai_addr, p->ai_addrlen);
        if (conerr == -1) {
            close(sockfd);
            continue; //can't connect, try next
        }
        break;
    }
    if (conerr == 0) {
        char ip[INET6_ADDRSTRLEN];
        inet_ntop(serverInfo->ai_family, serverInfo->ai_addr, ip, sizeof ip);

        #ifdef DEBUG
        cout << "Connecting to: " << ip << "\n";
        #endif

    }

    #ifdef DEBUG
    else cout << "Failed to connect\n";
    #endif
    
    freeaddrinfo(serverInfo);
}

void Client::Disconnect() {
    close(sockfd);
}

int Client::Send(void* data, int length) {
    return send(sockfd, data, length, 0);
}



int Client::Receive(void* buffer, int bufferSize) {
    bzero(buffer, bufferSize);
    int recverr = recv(sockfd, buffer, bufferSize, 0);
    return recverr;
}


